#!/bin/bash
# Run this script at the root folder of user's the data project
# Generates data, adds to DVC, commits to git, and pushes to DVC remote

set -e

# Function to print timestamped messages
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"
}

# Function to check if command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Function to get current username
get_username() {
    whoami
}

# Main demo function
run_dvc_demo() {
    local username=$(get_username)
    local timestamp=$(date '+%Y%m%d_%H%M%S')
    
    log "Starting DVC Push Demo for user: $username"
    log "Timestamp: $timestamp"
    
    # Check prerequisites
    if ! command_exists git; then
        log "ERROR: git is not installed or not in PATH"
        exit 1
    fi
    
    if ! command_exists dvc; then
        log "ERROR: dvc is not installed or not in PATH"
        exit 1
    fi
    
    if ! command_exists python3; then
        log "ERROR: python3 is not installed or not in PATH"
        exit 1
    fi
    
    # Check if we're in a git repository
    if ! git rev-parse --git-dir > /dev/null 2>&1; then
        log "ERROR: Not in a git repository. Please run this script from within a git repo."
        exit 1
    fi
    
    # Check if DVC is initialized
    if [ ! -f ".dvc/config" ]; then
        log "DVC not initialized. Initializing DVC..."
        dvc init
        log "DVC initialized successfully"
    fi
    
    python data_generator.py
    # List generated files
    log "Generated files:"
    ls -la data
    
    # Add data files to DVC
    log "Adding data files to DVC..."
    dvc add data/sales.csv

    # Check git status
    log "Git status after DVC add:"
    git status
    
    # Commit changes to git
    log "Committing changes to git..."
    local commit_message="Add dataset sales.csv by $username at $timestamp"
    git commit -m "$commit_message"

    # Push to DVC remote (if configured)
    if dvc remote list >/dev/null 2>&1; then
        log "Pushing to DVC remote..."
        dvc push
        log "DVC push completed successfully"
    else
        log "No DVC remote configured, skipping DVC push"
        log "To configure DVC remote, run: dvc remote add -d myremote <remote-url>"
    fi
}

# Script usage information
usage() {
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "DVC Push Demo Script"
    echo "Generates data, adds to DVC, commits to git, and pushes to DVC remote"
    echo ""
    echo "Options:"
    echo "  -h, --help     Show this help message"
    echo ""
    echo "Example:"
    echo "  $0"
    echo ""
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            usage
            exit 0
            ;;
        *)
            log "Unknown option: $1"
            usage
            exit 1
            ;;
    esac
    shift
done

# Run the demo
run_dvc_demo
